package com.mall.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.pojo.Order;
import com.mall.pojo.OrderDetail;
import com.mall.service.IOrderDetailService;
import com.mall.service.IOrderService;
import com.mall.service.IWaresService;
import com.mall.utils.AlipayUtil;
import com.mall.utils.InitDataUtil;
import com.mall.utils.R;
import com.mall.vo.OrderDetailVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理
 *
 * @author xiao-chen
 * @since 2023-04-20
 */
@Slf4j
@RestController
@RequestMapping("/order")
@SaCheckLogin
public class OrderController implements InitializingBean {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private InitDataUtil initDataUtil;
    @Resource
    private IOrderService orderService;
    @Resource
    private IOrderDetailService orderDetailService;
    @Resource
    private IWaresService waresService;
    @Resource
    private DefaultRedisScript<Long> decrScript;
    @Resource
    private AlipayUtil alipayUtil;

    /**
     * 根据子订单id查询订单支付状态
     *
     * @param orderId 子订单id
     * @return com.mall.utils.R<java.lang.String>
     * @author cxx
     * @date 2023/6/11 15:50
     */
    @GetMapping("/judgeByOrderId")
    public R<String> judgeByOrderId(@RequestParam(name = "orderId") Long orderId) throws AlipayApiException {
        OrderDetail orderDetail = orderDetailService.getById(orderId);
        if (ObjectUtils.isEmpty(orderDetail)) {
            return R.error("不存在该订单");
        }
        boolean b = alipayUtil.ckeckPay(orderDetail.getOrderId().toString());
        if (b) {
            return R.success("支付成功");
        }
        if (orderDetail.getIsPay().getCode() == 0) {
            return R.success("支付失败");
        }
        return R.success("未支付");

    }

    /**
     * 根据总订单id查询订单支付状态
     *
     * @param orderId 总订单id
     * @return com.mall.utils.R<java.lang.String>
     * @author cxx
     * @date 2023/6/11 15:50
     */
    @GetMapping("/judgeByAllOrderId")
    public R<String> judgeByAllOrderId(@RequestParam(name = "orderId") Long orderId) throws AlipayApiException {
        Order order = orderService.getById(orderId);
        if (ObjectUtils.isEmpty(order)) {
            return R.error("不存在该订单");
        }
        boolean b = alipayUtil.ckeckPay(order.getId().toString());
        if (b) {
            return R.success("支付成功");
        }
        if (order.getIsPay().getCode() == 0) {
            return R.success("支付失败");
        }
        return R.success("未支付");

    }

    /**
     * 根据子订单号查询订单信息
     *
     * @param orderId 子订单号
     * @return com.mall.utils.R<com.mall.vo.OrderDetailVo>
     * @author cxx
     * @date 2023/6/10 22:52
     */
    @GetMapping("/getOrderinfoById")
    public R<OrderDetailVo> getOrderinfoById(@RequestParam(name = "orderId") Long orderId) {
        OrderDetail orderDetail = orderDetailService.getById(orderId);
        if (ObjectUtils.isEmpty(orderDetail)) {
            return R.error("不存在该订单!");
        }
        OrderDetailVo detailVo = new OrderDetailVo();
        BeanUtils.copyProperties(orderDetail, detailVo);
        detailVo.setIsPay(orderDetail.getIsPay().getMsg());
        return R.success(detailVo);
    }

    /**
     * 获取用户支付成功历史订单
     *
     * @param
     * @return com.mall.utils.R<java.util.List < com.mall.pojo.OrderDetail>>
     * @author cxx
     * @date 2023/5/7 21:01
     */
    @GetMapping("/getsuccess")

    public R<List<OrderDetailVo>> getSuccessOrder() {

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getUserId, Long.valueOf(StpUtil.getLoginId().toString()))
                .and(i -> i.eq(OrderDetail::getIsPay, 2));
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        List<OrderDetailVo> collect = list.stream().map(item -> {
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            BeanUtils.copyProperties(item, orderDetailVo);
            orderDetailVo.setIsPay(item.getIsPay().getMsg());
            return orderDetailVo;
        }).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(collect)) {
            return R.success(collect);
        }
        return R.error("用户没有支付成功历史订单!");
    }

    /**
     * 获取用户过期订单，支付失败的订单
     *
     * @param
     * @return com.mall.utils.R<java.util.List < com.mall.pojo.OrderDetail>>
     * @author cxx
     * @date 2023/5/7 21:08
     */
    @GetMapping("/getexpired")

    public R<List<OrderDetailVo>> getExpired() {

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getUserId, Long.valueOf(StpUtil.getLoginId().toString()))
                .and(i -> i.eq(OrderDetail::getIsPay, 0));
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        List<OrderDetailVo> collect = list.stream().map(item -> {
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            BeanUtils.copyProperties(item, orderDetailVo);
            orderDetailVo.setIsPay(item.getIsPay().getMsg());
            return orderDetailVo;
        }).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(collect)) {
            return R.success(collect);
        }
        return R.error("用户没有支付失败历史订单!");
    }

    /**
     * 获取用户的所有订单
     *
     * @param
     * @return com.mall.utils.R<java.util.List < com.mall.pojo.OrderDetail>>
     * @author cxx
     * @date 2023/6/9 11:22
     */
    @GetMapping("/getAll")
    public R<List<OrderDetailVo>> getAll() {
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getUserId, Long.valueOf(StpUtil.getLoginId().toString()));
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        List<OrderDetailVo> collect = list.stream().map(item -> {
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            BeanUtils.copyProperties(item, orderDetailVo);
            orderDetailVo.setIsPay(item.getIsPay().getMsg());
            return orderDetailVo;
        }).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(collect)) {
            return R.success(collect);
        }
        return R.error("用户没有历史订单!");
    }

    //商品数量初始化
    @Override

    public void afterPropertiesSet() {
        initDataUtil.initData();
    }

    // 延迟15分钟执行，之后每隔15分钟执行一次
//    @Scheduled(initialDelay = 900000, fixedDelay = 900000)
//    public void refreshData() {
//        initDataUtil.initData();
//    }
}

